#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long; # use getopt for command line parameters
use Pod::Usage; # POD for usage information


#### Declaration of Variables  ###  this must be edited
my $Server='iospbc01.net120.os.itelligence.de';  #Networker Server
my $Client='amopbw10.net120.os.itelligence.de';  #Clientname
my $Pool='LOGMaxDB';  #Pool for example: LOGMaxDB
my $savedir='/sapdb/BW1/stdbarch';  #directory where the logs reside
my $second='/sapdb/BW1/stdbarch/2nd_copy';  #directory to copy the saved logs to :savedir/2nd_copy
my $logname='BW1_LOG';  #beginning of log-name example: SID_LOG
my $retent='2Weeks';  #retention of saved data
my $logfile='/nsr/applogs/nsrBW1_Libelle_logsave.log';  #path and filename of log



#### NO MODIFICATION BEYOND THIS POINT ####
## sub for moving files at the end of the save
sub move_files(){
my %args=@_;
my $sourcefile=$args{'source'};
my $destination="$args{'destination'}/";
my $move_files_rc=0;
$move_files_rc=system("/bin/mv $sourcefile $destination");
if ($?){
  chomp $move_files_rc;
  &logging(message=>"problem moving files: $move_files_rc");
  exit 1;
}
return $move_files_rc;
}

## sub for logging
sub logging(){
my %args=@_;
my $message=$args{'message'};
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
my $nice_timestamp = sprintf ( "%04d-%02d-%02d %02d:%02d:%02d",$year+1900,$mon+1,$mday,$hour,$min,$sec);
if (not -e $logfile){`/bin/touch $logfile`;}
open (LOGFILE,">>$logfile");
print LOGFILE "$nice_timestamp: $message\n";
close (LOGFILE);
}
##  Main
&logging(message=>"#################################");
&logging(message=>"Beginning logsave");
my $list=undef;
my @list=undef;
if (`/bin/ls $savedir/$logname* | wc -l` > 1){  #check for files
  @list=`/bin/ls -tr $savedir/$logname*`;  #creating list of files
  pop @list;  #deleting last modified file from list
  chomp @list;  #deleting newline
  $list=1;
}
my $save_rc=system("save -s $Server -b $Pool -y $retent -c $Client -m -q -N $savedir $savedir");  #saving files
if ($?){  #check if save was ok
  chomp $save_rc;
  &logging(message=>"save was aborted: $save_rc");
  exit 1;
}else {&logging(message=>"files saved successfully");}
`/bin/rm $second/$logname*`;
if ($list){
  foreach (@list){&move_files(source=>$_,destination=>$second);}
  &logging(message=>"finished moving logs");
}else {&logging(message=>"nothing to move");}
&logging(message=>"End of log-save-script");
exit 0;
